﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using PanasonicWarranty.Business;
using System.Web.UI.HtmlControls;
using Utils;
namespace PanasonicWarranty.UI
{
    public partial class WarrantyPackageManagement : BasePageManageWarranty
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                BindGridData();
            }
        }


        private void BindGridData()
        {
            try
            {
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRow = 0;
                string code = ddlSearchCode.SelectedValue;
                string name = "";
                int? period = string.IsNullOrWhiteSpace(txtSearchPeriod.Text) ?
                                            (int?)null :
                                            Convert.ToInt32(txtSearchPeriod.Text.Trim());
                string periodType = ddlSearchPeriodType.SelectedValue;
                bool? disabled = ddlSearchDisabled.SelectedValue == "" ? (bool?)null : bool.Parse(ddlSearchDisabled.SelectedValue);
                grvData.DataSource = pa_WarrantyPackage.Paging(currentPage, pageSize, ref totalRow, code, name, period, periodType, disabled);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRow;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                BindDropDownData();
                ltrInfo.Text = "Tổng cộng: " + totalRow;
            }
            catch { }
        }

        private void BindDropDownData()
        {
            BindDropDownListData(ddlSearchCode, DB.pa_WarrantyPackages.ToList(), "WarrantyPackageCode", "WarrantyPackageCode", new ListItem("", ""));
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName)
                {
                    case "Editing":
                        hdfID.Value = id.ToString();
                        var obj = DB.pa_WarrantyPackages.FirstOrDefault(p => p.WarrantyPackageID == id);
                        if (obj != null)
                        {
                            txtTypeCode.Enabled = false;
                            txtTypeCode.Text = obj.WarrantyPackageCode;
                            txtPeriod.Text = obj.WarrantyPeriod.ToString();
                            ddlPeriodType.SelectedValue = obj.PeriodType;
                            chkDisable.Checked = obj.Disabled ?? false;
                            txtDescription.Text = obj.Description;
                            RegisterStartUpScript("OpenDialog('dialog1',400);");
                        }
                        break;
                    case "Deleting":
                        Authorize(Role.Write);
                        var deletedObj = DB.pa_WarrantyPackages.FirstOrDefault(p => p.WarrantyPackageID == id);
                        if (deletedObj != null)
                        {
                            DB.pa_WarrantyPackages.DeleteOnSubmit(deletedObj);
                            DB.SubmitChanges();
                            //Ghi log dữ liệu
                            InsertChangeLog("Xóa dữ liệu gói bảo hành");
                            BindGridData();
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (ValidateInfo())
                {
                    pa_WarrantyPackage obj;
                    if (hdfID.Value == "0")
                    {
                        obj = new pa_WarrantyPackage();
                    }
                    else
                        obj = DB.pa_WarrantyPackages.FirstOrDefault(p => p.WarrantyPackageID == int.Parse(hdfID.Value));
                    obj.WarrantyPackageCode = txtTypeCode.Text.ToUpper();
                    obj.WarrantyPackageName = txtTypeCode.Text.ToUpper();
                    obj.WarrantyPeriod = Convert.ToInt32(txtPeriod.Text);
                    obj.PeriodType = ddlPeriodType.SelectedValue;
                    obj.Disabled = chkDisable.Checked;
                    obj.Description = txtDescription.Text;
                    if (hdfID.Value == "0")
                        DB.pa_WarrantyPackages.InsertOnSubmit(obj);
                    DB.SubmitChanges();
                    //Ghi log dữ liệu
                    InsertChangeLog(hdfID.Value == "0" ? "Thêm mới dữ liệu gói bảo hành" : "Cập nhật dữ liệu gói bảo hành");
                    BindGridData();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
            try
            {
                ControlClass.ResetControlValues(pnlDialogBlock);
                txtTypeCode.Enabled = true;
                hdfID.Value = "0";
                RegisterStartUpScript("OpenDialog('dialog1',400);");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected override bool ValidateInfo()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrWhiteSpace(txtTypeCode.Text))
                errMsg = "Bắt buộc nhập gói gia hạn";
            if (string.IsNullOrWhiteSpace(txtPeriod.Text))
                errMsg = "Bắt buộc nhập thời hạn hành";
            //check trùng mã
            if (DB.pa_WarrantyPackages.Any(p => p.WarrantyPackageCode == txtTypeCode.Text.Trim() && p.WarrantyPackageID != int.Parse(hdfID.Value)))
                errMsg = "Mã đã bị trùng, xin mời nhập mã khác!";
            if (errMsg != string.Empty)
            {
                lbError.Text = errMsg;
                RegisterStartUpScript("OpenDialog('dialog1',400);");
                return false;
            }
            else
            {
                lbError.Text = string.Empty;
                return true;
            }
        }
    }
}